import React, { Component } from 'react'
import Lists from '../components/Lists'

export default class Cart extends Component {

  // 数据 状态
  state = {
    carts: [
      { id: 1, name: '苹果11', price: 10, num: 1 },
      { id: 2, name: '小米10', price: 20, num: 1 },
      { id: 3, name: '华为meta40', price: 30, num: 1 }
    ]
  }


  render() {
    return (
      <div>
        {/* 功能组件 */}
        <Lists carts={this.state.carts} handlerCartNum={this.handlerCartNum.bind(this)} />
      </div>
    )
  }

  handlerCartNum(index, flag = 'incr') {
    let carts = this.state.carts

    if ('incr' === flag) {
      carts[index].num++
      /* this.setState({
        carts
      }) */
      /* this.setState(state=>{
        return {
          carts
        }
      }) */
    } else {
      // splice删数组中的数据影响原数组
      carts.splice(index, 1)
    }
    
    this.setState(state => ({ carts }))
  }
}
